<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import planApi from "@/api/planApi";
import testResultApi from "@/api/testResultApi";
import constants from "@/utils/constants";
import Upload from "@/components/Upload.vue";
import { Message } from "@arco-design/web-vue";
import dayjs from "dayjs";
import tool from "@/utils/tool"

const router = useRouter();

const submitForm = ref();
const searchForm = ref();
const historyParams = history.state.params;
const searchModel = reactive({
  planId: historyParams.planId,
});
const visible = ref(false);
const uploadVisible = ref(false);
const uploadHistoryVisible = ref(false);
const downloading = ref(false);
const loading = ref(false);

const plan = ref(Object.assign({}, historyParams));

let uploadData = ref({
  planId: historyParams.planId,
});
let schoolList = ref([]);
let gradeClassesList = ref([]);
let classesList = ref([]);

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

const columns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 180,
    fixed: "left",
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    fixed: "left",
    width: 90,
  },
  {
    title: "性别",
    slotName: "sex",
    fixed: "left",
    width: 60,
  },
  {
    title: "年级",
    dataIndex: "gradeId",
    fixed: "left",
    width: 70,
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
    fixed: "left",
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
    fixed: "left",
  },
  {
    title: "测试项目",
    dataIndex: "prjName",
    width: 150,
  },
  {
    title: "成绩",
    dataIndex: "result",
    width: 150,
  },
  {
    title: "标准分",
    dataIndex: "standardScore",
    width: 120,
  },
  {
    title: "附加分",
    dataIndex: "extraScore",
    width: 120,
  },
  {
    title: "得分",
    dataIndex: "score",
    width: 100,
  },
  {
    title: "项目权重分",
    dataIndex: "finalScore",
    width: 120,
  },
  {
    title: "等级",
    dataIndex: "level",
    width: 100,
  },
  {
    title: "设备编号",
    dataIndex: "deviceNo",
    width: 200,
  },
  {
    title: "测试开始时间",
    dataIndex: "testStartTime",
    width: 180,
  },
  {
    title: "测试结束时间",
    dataIndex: "testEndTime",
    width: 180,
  },
  {
    title: "上传时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 90,
  },
];
const data = ref([]);

const scroll = {
  x: 1800,
  y: 600,
};

const showAddDialog = () => {
  visible.value = true;
  submitForm.value.resetFields();
  submitData.value = {
    schoolId: historyParams.schoolId,
    sex: "1",
  };
};

const showUploadDialog = () => {
  uploadVisible.value = true;
};

const showUploadHistoryDialog = () => {
  uploadHistoryVisible.value = true;
}

const downloadExcel = () => {
  downloading.value = true;
  planApi.downloadReportFile(searchModel).then((res) => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    const fileName =
      "【" +
      schoolName +
      "】体测成绩上报-" +
      dayjs().format("YYYYMMDDHHmmss") +
      ".zip";

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    downloading.value = false;
  });
};

const closeUploadDialog = () => {
  uploadVisible.value = false;
  uploadHistoryVisible.value = false;
  refresh();
};

let schoolName = "";
const schoolSelectChange = (schoolId) => {
  if (schoolId) {
    console.log(schoolList);
    let school = schoolList.value.find((item) => {
      return item.id == schoolId;
    });
    if (school) {
      schoolName = school.name;
    }
    planApi
      .getGradeClassesList({
        planId: historyParams.planId,
        schoolId: schoolId,
      })
      .then((res) => {
        gradeClassesList.value = res;
      });
  } else {
    gradeClassesList.value = [];
    classesList.value = [];
    searchModel.classesId = "";
    searchModel.gradeId = "";
  }
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.children && gradeModel.children.length > 0) {
    classesList.value = gradeModel.children;
  } else {
    searchModel.classesId = "";
    classesList.value = [];
  }
};

const deleteRecord = (record) => {
  testResultApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      refresh();
    });
};

const getSchoolList = () => {
  planApi
    .getSchoolList({
      planId: historyParams.planId,
    })
    .then((res) => {
      schoolList.value = res;
    });
};

const search = () => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  testResultApi.page(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search();
};

const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.classesId = "";
  searchModel.gradeId = "";
  searchModel.testStartTime = "";
  searchModel.testEndTime = "";
  searchModel.searchTimes = [];
  gradeClassesList.value = [];
  classesList.value = [];
};

let permissions = tool.data.get('permissions');

const hasPermission = (code) => {
  return permissions.includes(code);
}

const calculating = ref(false);
const clearing = ref(false);
const calculate = () => {
  calculating.value = true;
  testResultApi.calculate(searchModel).then(res => {
    Message.success("计算完成");
    calculating.value = false;
  })
}


const updateResultToParent = () => {
  calculating.value = true;
  testResultApi.updateParentPlanTest(searchModel).then(res => {
    Message.success("更新完成");
    calculating.value = false;
  })
}

const clearData = () => {
  clearing.value = true;
  testResultApi.clearData(searchModel).then(res => {
    Message.success("清空完成");
    clearing.value = false;
  })
}

const onSearchTimeChange = (times) => {
  if (times && times.length == 2) {
    searchModel.testStartTime = times[0];
    searchModel.testEndTime = times[1];
  }
}

search();
getSchoolList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>体测管理</a-breadcrumb-item>
        <a-breadcrumb-item>成绩上传及更新记录</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item field="schoolId" label="学校">
                  <a-select v-model="searchModel.schoolId" placeholder="请选择学校" allow-clear @change="schoolSelectChange">
                    <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                      :label="school.name"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="gradeId" label="年级/班级">
                  <a-space>
                    <a-select style="width: 120px" v-model="searchModel.gradeId" @change="changeSelectGrade"
                      placeholder="年级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name
                      }}</a-option>
                    </a-select>
                    <a-select style="width: 120px" v-model="searchModel.classesId" placeholder="班级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="classes in classesList" :key="classes.id" :value="classes.id">{{ classes.name
                      }}</a-option>
                    </a-select>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="学生姓名">
                  <a-input v-model="searchModel.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="prjName" label="项目">
                  <a-input v-model="searchModel.prjName" placeholder="请输入项目名称查询"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="sex" label="性别">
                  <a-select v-model="searchModel.sex" placeholder="请选择性别">
                    <a-option value="">全部</a-option>
                    <a-option value="1">男</a-option>
                    <a-option value="2">女</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="studyCode" label="学籍号">
                  <a-input v-model="searchModel.studyCode" placeholder="请输入学籍号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="searchTimes" label="测试时间">
                  <a-range-picker v-model="searchModel.searchTimes" showTime @change="onSearchTimeChange"
                    :placeholder="['测试开始时间', '测试结束时间']" :style="{ width: '100%' }" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search()">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <a-card style="margin-top: 20px">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" @click="showUploadDialog">
            <template #icon>
              <icon-upload />
            </template>
            导入成绩
          </a-button>
          <a-button v-if="!plan.examFlag" type="primary" @click="showUploadHistoryDialog">
            <template #icon>
              <icon-upload />
            </template>
            导入历史成绩
          </a-button>
          <a-tooltip content="选择上方学校才可操作">
            <a-button @click="downloadExcel" :loading="downloading" :disabled="!searchModel.schoolId">
              <template #icon>
                <icon-download />
              </template>
              {{ downloading ? '正在导出成绩' : '导出上报成绩' }}
            </a-button>
          </a-tooltip>
          <a-popconfirm content="确认要重新计算成绩吗？" @ok="calculate">
            <a-button :loading="calculating" v-if="hasPermission('calculate')">
              <template #icon>
                <icon-computer></icon-computer>
              </template>
              {{ calculating ?
                '正在计算..' :
                '计算成绩' }}</a-button>
          </a-popconfirm>
          <a-popconfirm content="确认要清空所有已有成绩吗？" @ok="clearData">
            <a-button :loading="clearing" v-if="hasPermission('clearData')">
              <template #icon>
                <icon-delete></icon-delete>
              </template>
              {{ clearing ?
                '正在清空..' :
                '清空成绩' }}</a-button>
          </a-popconfirm>
          <a-popconfirm content="确认要更新成绩至原计划吗？" @ok="updateResultToParent">
            <a-button :loading="calculating" v-if="hasPermission('calculate') && plan.examFlag && plan.parentId != 0">
              <template #icon>
                <icon-computer></icon-computer>
              </template>
              {{ calculating ?
                '正在更新..' :
                '更新成绩至原计划' }}</a-button>
          </a-popconfirm>
        </a-space>
      </div>
      <a-table :columns="columns" row-key="id" :scroll="scroll" :loading="loading" :data="data"
        @page-change="pagination.pageChange" @page-size-change="pagination.pageSizeChange" :pagination="pagination"
        :bordered="false">
        <template #nation="{ record }">
          {{ getNationName(record.nation) }}
        </template>
        <template #sex="{ record }">
          {{ record.sex == "1" ? "男" : " 女" }}
        </template>
        <template #action="{ record }">
          <a-space>
            <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
              <a-button type="text">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>

  <a-modal v-model:visible="uploadVisible" title="导入测试成绩数据" hide-cancel width="600px" @ok="closeUploadDialog">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        <div>本平台为互联网非涉密平台，严禁处理、传输国家秘密、工作秘密及敏感信息。请确认扫描、传输的文件资料不涉及上述信息。</div>
        暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传
      </div>
      <a-button type="link" href="/成绩上传模板.xlsx" style="margin-bottom: 10px">导入成绩模板下载</a-button>
      <Upload :uploadData="uploadData" :draggable="true" accept=".xls,.xlsx"
        action="/admin/v1/testResult/importTestData" />
    </a-space>
  </a-modal>

  <a-modal v-model:visible="uploadHistoryVisible" title="导入历史成绩数据" hide-cancel width="600px" @ok="closeUploadDialog">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传
      </div>
      <Upload :uploadData="uploadData" :draggable="true" accept=".xls,.xlsx"
        action="/admin/v1/testResult/importTestLineData" />
    </a-space>
  </a-modal>

</template>

<style scoped></style>
